﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Akronus.TaskScheduler
{
    /// <summary>
    /// Manages task schedule if task is scheduled to run on intervals.
    /// </summary>
    public class IntervalTaskScheduleStrategy : ITaskScheduleStrategy
    {
        private double interval;

        private string taskName;

        private ITaskInfoDataService dataService;

        /// <summary>
        /// Initializes a new instance of the <see cref="IntervalTaskRunStrategy"/> class.
        /// </summary>
        /// <param name="taskName">Name of the task.</param>
        /// <param name="interval">The interval.</param>
        /// <param name="dataService">The data service.</param>
        public IntervalTaskScheduleStrategy(string taskName, double interval, ITaskInfoDataService dataService)
        {
            this.dataService = dataService;
            this.taskName = taskName;
            this.interval = interval;
        }

        /// <summary>
        /// Gets the task schedule.
        /// </summary>
        /// <returns>the <see cref="TaskSchedule"/>.</returns>
        public virtual TaskSchedule GetTaskSchedule()
        {
            var taskInfo = dataService.GetTaskInfo(taskName);
            if (taskInfo != null)
            {
                var timeSinceLastRun = DateTime.Now.Subtract(taskInfo.LastRunTime);
                if (timeSinceLastRun.TotalMilliseconds >= this.interval)
                {
                    return new TaskSchedule() { Interval = this.interval, RunTaskImmediately = true };
                }
                else
                {
                    return new TaskSchedule() { Interval = this.interval - timeSinceLastRun.TotalMilliseconds, RunTaskImmediately = false };
                }
            }
            else
            {
                return new TaskSchedule() { Interval = this.interval, RunTaskImmediately = true };
            }
        }
    }
}
